package tpf.designer.pattern.course5.structure_pattern2.flyweight_13.simple;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FlyweightFactorySingleton {
    private HashMap flies = new HashMap();
    private static FlyweightFactorySingleton myself = new FlyweightFactorySingleton();

    private FlyweightFactorySingleton() {
    }

    /**
     * 静态工厂，向外界提供唯一的实例
     * @return
     */
    public static FlyweightFactorySingleton getInstance(){
        return myself;
    }

    public synchronized Flyweight factory(Character state){
        if (flies.containsKey(state)){
            return (Flyweight) flies.get(state);
        } else {
            Flyweight fly = new ConcreteFlyweight(state);
            flies.put(state,fly);
            return fly;
        }
    }

    /**
     * 辅助方法
     */
    public void checkFlyweight(){
        Flyweight fly;
        int i = 0;
        System.out.println("\n===================checkFlyweight===================\n");
        for (Iterator it = flies.entrySet().iterator(); it.hasNext(); ){
            Map.Entry e = (Map.Entry)it.next();
            System.out.println("享元对象" + (++i) + ":" + e.getKey());
        }
        System.out.println("\n===================checkFlyweight===================\n");
    }

}
